//index.js
//获取应用实例
const app = getApp()
let request = require('../../utils/request.js')
import * as echarts from '../../components/ec-canvas/echarts';

Page({
  data: {
    barHeight: wx.getMenuButtonBoundingClientRect().bottom,
    pageHeight: app.globalData.pageHeight,
    paddingTop: app.globalData.paddingTop,
    changeParkingDialog: false,
    handrailDialog: false,
    parkInfo: {},
    parkingOwnerData: {},
    parkList: [],
    parkName: '',
    parkId: '',
    parkSource: '',
    aisleList: [],
    selectAisleData: {},
    infoShow: true,
    userId: null,
    username: null,
    phoneNumber: null,
    shopId: null,
    managerName: null,
    telephone: null,
    shopName: null,
    todayRevenue: 0,
    checkDate: 1,
    writeOffRevenue: 0,
    LinkIndexMax: 0,
    LinkIndexMin: 0,
    dialogShow: false,
    writeOffContent: null,
    orderCode: null,
    writeOffRecord: [],
    searchRecordCode: null,
    shopList: [],
    investAmount: 0,
    chart: null,
    ecLine: {
      lazyLoad: true,
      // 初始化图表
      onInit: (canvas, width, height)=> {
        //初始化echarts元素，绑定到全局变量，方便更改数据
        this.chart = echarts.init(canvas, null, {
          width: width,
          height: height
        });
        canvas.setChart(this.chart);
        return chart;
      }
    },
  },
  onLoad: function () {
    console.log('右上角的胶囊按钮的信息：', this.data.barHeight)
  },
  onReady: function () {
    this.getShopByManageId(this.data.userId)
  },
  onShow() {
    this.setData({
      userId: wx.getStorageSync('lmtc_shop_userId'),
      username: wx.getStorageSync('username'),
      phoneNumber: wx.getStorageSync('phoneNumber')
    })
  },
  /**
   * 引流投入
   */
  invest(dateType){
    request.http('/shop/shop-order/invest', 'GET', { dateType: dateType, shopId: this.data.shopId })
      .then(res => {
        let data = res.data
        if (data.code == 200) {
          this.setData({
            investAmount: data.data
          })
        }
      })
  },
  /**
   * 收入详情、核销记录
   */
  tabCut(e) {
    let val = e.currentTarget.dataset.s
    this.setData({ infoShow: val })
    if (!val) {
      this.getWriteOffPage(); //  查询核销记录
    } else {
      this.getLinkIndex() //  总收益环比分析
    }
  },
  /**
   * 手动核销
   */
  manualWriteOff() {
    this.setData({
      dialogShow: true
    })
  },
  /**
   * 昨日、今日、本周、本月
   */
  chechDateSee(e) {
    let val = e.currentTarget.dataset.s
    this.setData({
      checkDate: val
    })
    this.seeWriteOffRevenue(val);
    this.invest(val)  //  引流投入
  },
  /**
   * 查询核销收入 昨日、今日、本周、本月
   */
  seeWriteOffRevenue(type) {
    request.http('/shop/shop-order/write-off-revenue', 'GET', { dateType: type, shopId: this.data.shopId })
      .then(res => {
        let data = res.data
        if (data.code == 200) {
          this.setData({
            writeOffRevenue: data.data
          })
        }
      })
  },

  /**
   * 根据用户ID查询商户
   */
  getShopByManageId(id) {
    request.http('/shop/shop-info/get-by-manage-id', 'GET', { manageId: id })
      .then(res => {
        console.log('店铺信息：', res)
        let data = res.data
        if (data.code == 200) {
          this.setData({
            shopName: wx.getStorageSync('shopName') == '' ? data.data[0].shopName : wx.getStorageSync('shopName'),
            shopId: wx.getStorageSync('shopId') == '' ? data.data[0].id : wx.getStorageSync('shopId'),
            managerName: wx.getStorageSync('username') == '' ? data.data[0].username : wx.getStorageSync('username'),
            telephone: wx.getStorageSync('telephone') == '' ? data.data[0].telephone : wx.getStorageSync('telephone'),
            shopList: data.data
          })
          console.log('店铺id：', wx.getStorageSync('shopId'))
          wx.setStorageSync('shopName', this.data.shopName) 
          wx.setStorageSync('shopId', this.data.shopId) 
          wx.setStorageSync('username', this.data.username) 
          wx.setStorageSync('telephone', this.data.telephone) 

          this.getTodayRevenue(this.data.shopId) //  今日收益
          this.invest(1)
          this.seeWriteOffRevenue(1)
          this.getLinkIndex()
        }
      })
  },

  /*
  * 查询今日收益
  */
  getTodayRevenue(id) {
    request.http('/shop/shop-order/today-revenue', 'GET', { shopId: id })
      .then(res => {
        let data = res.data
        if (data.code == 200) {
          this.setData({
            todayRevenue: data.data
          })
        }
      })
  },
  /**
   * 扫码核销
   */
  scanCode() {
    let _this = this
    wx.scanCode({
      onlyFromCamera: true,
      success(res) {
        let data = res.result
        _this.setData({
          dialogShow: true,
          orderCode: data
        })
        //  获取核销码信息
        _this.getByWriteOffCode(data);
      }
    })
  },
    /**
   * 根据核销码查询商户订单详情
   */
  getByWriteOffCode(e) {
    console.log('商户id：', this.data.shopId)
    let code = e.detail ? e.detail.value : e
    if(code.length == 16){
      let url = '/shop/shop-order/get-by-write-off-code'
      let parmas = { writeOffCode: code, shopId: this.data.shopId }
      request.http(url, 'GET', parmas)
      .then(res => {
        let data = res.data
        console.log('核销码信息：', data)
        if (data.code == 200) {
          this.setData({
            writeOffContent: data.data
          })
        }
      })
    }
  },
  /**
   * 确认核销
   */
  submit(id) {
    console.log('商户id：', this.data.shopId)
    if(this.data.writeOffContent == null || this.data.writeOffContent.id == null){
      wx.showToast({
        icon: 'none',
        title: '核销码错误',
      })
      return
    }
    request.http('/shop/shop-order/write-off-code', 'GET', { id: this.data.writeOffContent.id, shopId: this.data.shopId })
    .then(res => {
      let data = res.data
      if(data.code == 200) {
        wx.showToast({ title: '核销成功' })
        this.setData({
          dialogShow: false,
          writeOffContent: {},
          orderCode: ''
        })

        //  根据用户ID查询商户
        this.getShopByManageId(this.data.userId)
      }
    })
  },
  /**
   * 关闭核销弹窗
   */
  closeDialog() {
    this.setData({
      dialogShow: false,
      writeOffContent: {},
      orderCode: ''
    })
  },

  /**
   * 今日收益
   */
  getToadyMoney(parkId) {
    let that = this
    let url = '/order/orderInfo/getParkTodayRevenue'
    let parmas = {
      parkId: that.data.parkId ? that.data.parkId : parkId
    }
    request.http(url, 'GET', parmas)
      .then(res => {
        let data = res.data
        if (data.code == 200) {
          that.setData({
            'parkInfo.todayMoney': data.data
          })
        }
      })
  },
  /**
   * 获取核销记录订单号
   */
  searchRecord(e) {
    this.setData({
      searchRecordCode: e.detail.value
    })
  },
  /**
   * 查询核销记录
   */
  getWriteOffPage() {
    let searchForm = {
      shopId: this.data.shopId,
      currentPage: 1,
      pageSize: 10
    }
    if(this.data.searchRecordCode) {
      searchForm.orderCode = this.data.searchRecordCode
    }
    request.http('/shop/shop-order/write-off-page', 'GET', searchForm)
      .then(res => {
        let data = res.data
        if(data.code == 200) {
          this.setData({
            writeOffRecord: data.data.records
          })
        }
      })
  },
  /**
  * 总收益环比分析
  */
  getLinkIndex() {
    let that = this
    let url = '/shop/shop-order/get-month-income'
    let parmas = {
      shopId: this.data.shopId
    }
    request.http(url, 'GET', parmas)
      .then(res => {
        let data = res.data
        if (data.code == 200) {
          let earnings = data.data
          var earningArr = []
          for (var i = 0; i < earnings.length; i++) {
            earningArr.push([earnings[i], i + 1])
          }
          earningArr.sort(function (a, b) {
            return a[0] - b[0]
          })
          that.setData({
            LinkIndexMax: earningArr[earningArr.length - 1],
            LinkIndexMin: earningArr[0]
          })

          this.mychartEcLine = this.selectComponent('#mychart-ecLine');
          this.mychartEcLine.init((canvas, width, height, dpr) => {
            // 获取组件的 canvas、width、height 后的回调函数
            // 在这里初始化图表
            const chart = echarts.init(canvas, null, {
              width: width,
              height: height,
              devicePixelRatio: dpr // new
            });
            // ec渲染初始化图表之后再来这里去调取数据挂载上去
            setTimeout(() => {
              getOption(chart, earnings);
              // 将图表实例绑定到 this 上，可以在其他成员函数（如 dispose）中访问
              this.chart = chart;
              // 注意这里一定要返回 chart 实例，否则会影响事件处理等
              return chart;
            }, 200)           
          });
        }
      })
  },
  /**
   * 更换店铺
   */
  changeShop() {
    this.setData({
      changeParkingDialog: true
    })
  },
  /**
   * 关闭切换停车场弹窗
   */
  hiddenChangeParkingDialog() {
    this.setData({
      changeParkingDialog: false
    })
  },
  /**
   * 选择店铺
   */
  selectShop(e) {
    let id = e.currentTarget.dataset.id
    this.getShopById(id)
    this.hiddenChangeParkingDialog()
  },
  /**
   * 获取商户
   */
  getShopById(id){
    request.http('/shop/shop-info/get-by-id', 'Get', { id: id })
      .then(res => {
        console.log('获取商户信息：', res)
        let data = res.data
        if (data.code == 200) {
          this.setData({
            shopName: data.data.shopName,
            shopId: data.data.id,
            managerName: data.data.username,
            telephone: data.data.telephone,
          })
          wx.setStorageSync('shopName', this.data.shopName) 
          wx.setStorageSync('shopId', this.data.shopId) 
          wx.setStorageSync('managerName', this.data.username) 
          wx.setStorageSync('telephone', this.data.telephone) 

          this.getTodayRevenue(data.data.id) //  今日收益
          this.invest(1)  //  
          this.seeWriteOffRevenue(1)
          this.getLinkIndex()
        }
      })
  },
  /**
   * 待办事项提示点
   */
  getTodoCount() {
    let that = this
    request.http('/order/orderInfo/getTodoCount', 'Get', { parkId: this.data.parkId })
      .then(res => {
        let data = res.data
        if (data.code == 200) {
          that.setData({
            'parkingOwnerData.todoCount': data.data
          })
        }
      })
  },
  /**
   * 预约申请提示点
   */
  getReserveCount() {
    let that = this
    request.http('/order/orderInfo/getReserveCount', 'Get', { parkId: this.data.parkId })
      .then(res => {
        let data = res.data
        if (data.code == 200) {
          that.setData({
            'parkingOwnerData.reserveCount': data.data
          })
        }
      })
  },
  /**
   * 预约页面跳转
   */
  toApply() {
    let parkInfo = wx.getStorageSync('lmtc_admin_parkInfo')
    let isOpen = parkInfo.reserveStatus
    if (isOpen == 1) {
      wx.redirectTo({
        url: '/pages/apply/apply',
      })
    } else {
      wx.showModal({
        title: '操作确认',
        content: '当前车场预约功能未开启，是否开启车位预约功能？',
        cancelText: '暂不开启',
        confirmText: '开启预约',
        success(res) {
          if (res.confirm) {
            let parmas = {
              parkId: parkInfo.parkId,
              status: 1
            }
            request.http('/promotion/reserve-rule/updateReserveStatus', 'POST', parmas)
              .then(res => {
                let data = res.data
                if (data.code == 200) {
                  parkInfo.reserveStatus = 1
                  wx.setStorageSync('lmtc_admin_parkInfo', parkInfo)
                  wx.redirectTo({
                    url: '/pages/apply/apply?firstOpen=true',
                  })
                }
              })
          }
        }
      })
    }
  },
  /**
   * 获取通道码
   */
  openHandrailDialog() {
    let that = this
    request.http('/park/park-entrance/getParkChannels', 'POST', { parkId: this.data.parkId, parkSource: this.data.parkSource })
      .then(res => {
        let data = res.data
        if (data.code == 200) {
          if (data.data.status == 1) {
            that.setData({
              aisleList: data.data.channels,
              handrailDialog: true
            })
          } else {
            wx.showToast({
              title: data.data.msg,
              icon: 'none'
            })
          }
        }
      })
  },
  /**
   * 关闭抬杆弹窗
   */
  closeHandrailDialog() {
    this.setData({
      handrailDialog: false,
      selectAisleData: {}
    })
  },
  /**
   * 选择通道
   */
  selectAisle(e) {
    let index = e.currentTarget.dataset.index
    let aisleList = this.data.aisleList
    this.setData({
      selectAisleData: aisleList[index]
    })
  },
  /**
   * 累计收入
   */
  getTotalRevenue() {
    let that = this
    request.http('/order/orderInfo/getTotalRevenue', 'GET', { parkId: this.data.parkId })
      .then(res => {
        let data = res.data
        if (data.code == 200) {
          that.setData({
            'parkingOwnerData.totalRevenue': data.data
          })
        }
      })
  },
    /**
   * 更换停车场
   */
  changeParking() {
    this.setData({
      changeParkingDialog: true
    })
  },
    /**
   * 关闭切换停车场弹窗
   */
  hiddenChangeParkingDialog() {
    this.setData({
      changeParkingDialog: false
    })
  }
})
function getOption(chart, xData) {
  var option = {
    color: ['#3398DB'],
    tooltip: {
      trigger: 'axis',
      axisPointer: {            // 坐标轴指示器，坐标轴触发有效
        type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
      }
    },
    grid: {    
      left: 20,
      right: 20,
      bottom: 15,
      top: 15,
      containLabel: true
    },
    xAxis: [
      {
        type: 'category',
        data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
        axisTick: {
          alignWithLabel: true
        }
      }
    ],
    yAxis: [ { type: 'value'} ],
    series: [
      {
        itemStyle: {
          // normal是柱状图的正常样式
          normal: {
            barBorderRadius: [30, 30, 0, 0],
            color: new echarts.graphic.LinearGradient(
              0, 0, 0, 1, [
              {
                offset: 1,
                color: '#5273F7'
              },
              {
                offset: 1,
                color: '#859DFF'
              }
            ]
            ),
          },
          // 移入当前的柱状图时改变颜色
          emphasis: {
            color: '#5273F7',
          }
        },
        type: 'bar',
        barWidth: '60%',
        data: xData
      }
    ]
  };

  chart.setOption(option);
}
